<?php

namespace Lib;

use Exception;

class View implements ViewInterface
{	
	protected $template;

	protected $variables;

	protected $layout = true;

	public function __construct($template = null, array $variables = null)
	{
		$this->variables = $variables;

		if ($template != null) {
			$this->template = $template;
			$this->render();
		}
	}

	public function render()
	{
		$path = $this->template . '.html';	
				
		if ($this->layout === false) {
			$this->loadTemplate($path);
			return;
		}

		$config = $this->getLayoutConfig();

		$this->loadTemplates(
			$config->offsetGet('up')
		);

		$this->loadTemplate($path);

		$this->loadTemplates(
			$config->offsetGet('down')
		);
	}

	public function setTemplate($template)
	{
		$this->template = $template;
		return $this;
	}

	public function setLayout(boolean $layout)
	{
		$this->layout = $layout;
		return $this;
	}

	protected function getLayoutConfig()
	{
		return require_once 'Config/layout.config.php';
	}

	protected function loadTemplate($template)
	{
		$file = 'View/'.$template;

		if (!file_exists($file)) {
			throw new Exception('Template: ' . $file . ' nao encontrado!');
		}
		require_once $file;
	}

	protected function loadTemplates(array $templates)
	{
		if (count($templates) < 1) {
			return;
		}

		foreach ($templates as $template) {
			$this->loadTemplate($template);
		}
	}
}

